-module(token).

-export([
    init/0

    ,make/1
    ,make_multi/1
    ,get/1
    ,destroy/1

    ,print/0
]).

-include("common.hrl").


%%%===================================================================
%%% API functions
%%%===================================================================

init() ->
    ets:new(?MODULE, [set, named_table, public, {keypos, 1}, {read_concurrency, true}]).


make(Id) ->
    destroy_by_id(Id),
    make_real(Id).

make_multi(Id) ->
    make_real(Id).

get(Token) ->
    case ets:lookup(?MODULE, Token) of
        [{Token, Id}] -> Id;
        _ -> undefined
    end.

destroy(Token) ->
    ets:delete(?MODULE, Token).


print() ->
    print(ets:first(?MODULE)).
print('$end_of_table') ->
    ok;
print(Token) ->
    [{Token, Id}] = ets:lookup(?MODULE, Token),
    ?ECHO("Token:~w,Id:~w", [Token, Id]),
    print(ets:next(?MODULE, Token)).


%%%===================================================================
%%% Internal functions
%%%===================================================================

make_real(Id) ->
    Num1 = util_math:rand(1, 65535),
    Num2 = util_math:rand(1, 65535),
    <<Token:32/big-integer-unsigned>> = <<Num1:16/big-integer-unsigned, Num2:16/big-integer-unsigned>>,

    ets:insert(?MODULE, {Token, Id}),

    Token.

destroy_by_id(Id) ->
    ets:match_delete(?MODULE, {'_', Id}).
